import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { hasToken } from '@/utils/token';

// 路由规则
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/account/Login.vue'),
        meta: { requiresAuth: false } // 无需登录
    },
    {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { requiresAuth: true } // 需要登录
    },
    {
        path: '/factories',
        name: 'Factories',
        component: () => import('@/views/factories/index.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/warehouse',
        name: 'Warehouse',
        component: () => import('@/views/warehouse/index.vue'),
        meta: { requiresAuth: true }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 全局路由守卫（检查Token）
router.beforeEach((to, _, next) => {
    // 未登录且需要授权的页面，重定向到登录页
    if (to.meta.requiresAuth && !hasToken()) {
        next('/login');
    } else {
        next();
    }
});

export default router;
